package com.xszx.serviceedu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xszx.servicebase.exceptionhandler.QinXueException;
import com.xszx.serviceedu.client.OssClient;
import com.xszx.serviceedu.entity.Course;
import com.xszx.serviceedu.entity.CourseDescription;
import com.xszx.serviceedu.entity.form.CourseInfoForm;
import com.xszx.serviceedu.entity.query.CourseQuery;
import com.xszx.serviceedu.entity.vo.CoursePublishVo;
import com.xszx.serviceedu.entity.vo.CourseQueryVo;
import com.xszx.serviceedu.entity.vo.CourseWebVo;
import com.xszx.serviceedu.mapper.CourseMapper;
import com.xszx.serviceedu.service.ChapterService;
import com.xszx.serviceedu.service.CourseDescriptionService;
import com.xszx.serviceedu.service.CourseService;
import com.xszx.serviceedu.service.VideoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author 白熊
 * @since 2024-07-16
 */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements CourseService {

    //导入课程简介相关的,因为课程简介和课程同属于一个业务,但是是两个不同的表
    @Autowired
    private CourseDescriptionService courseDescriptionService;
    @Autowired
    private VideoService videoService;
    @Autowired
    private ChapterService chapterService;
    @Autowired
    private OssClient ossClient;

    @Override//前台通过课程id查询课程讲师,课程详细信息以及课程大纲
    public CourseWebVo selectInfoWebById(String id) {
        this.updatePageViewCount(id);
        CourseWebVo courseWebVo = baseMapper.selectInfoWebById(id);
        return courseWebVo;
    }

    @Override
    public void updatePageViewCount(String id) {
        Course course = baseMapper.selectById(id);
        course.setViewCount(course.getViewCount() + 1);//浏览量+1
        baseMapper.updateById(course);
    }

    @Override
    @CacheEvict(value = "course",allEntries = true)
    public String saveCourseInfo(CourseInfoForm courseInfoForm) {//courseInfoForm是前端传过来的课程信息
        // 添加课程信息
        Course course = new Course();
        course.setStatus(Course.COURSE_DRAFT);//设置课程状态 默认是未发布
        BeanUtils.copyProperties(courseInfoForm,course);
        int insert = baseMapper.insert(course);//添加课程信息走insert
        if(insert==0){
            throw new QinXueException(20001,"添加课程信息失败");
        }

        // 保存课程详情信息
        CourseDescription courseDescription = new CourseDescription();
//        BeanUtils.copyProperties(courseInfoForm,courseDescription);
        courseDescription.setId(course.getId());
        courseDescription.setDescription(courseInfoForm.getDescription());


        //详细信息id是INPUT类型,比需要手动给过去
        //不能走这个方法,因为这个类是课程基本信息的类,走的话是课程基本信息的添加
//        baseMapper.insert(courseDescription);
        boolean save = courseDescriptionService.save(courseDescription);
        if(!save){
            throw new QinXueException(20001,"添加课程详细信息失败");
        }
        return course.getId();//返回添加的id,是为了前端假如回退回上一步,可以回显
    }

    @Override//根据id回显数据
    public CourseInfoForm getCourseInfoFormById(String id) {
        //查询课程根据id 因为是Course类,所以可以直接这样
        Course course = this.getById(id);
        if(course==null){
            throw new QinXueException(20001,"该课程编号不存在");
        }
        //创建课程详细信息列表
        CourseInfoForm courseInfoForm = new CourseInfoForm();
        //将课程详细信息列表用对应id获取到的course信息填充
        BeanUtils.copyProperties(course,courseInfoForm);

        //根据id获取课程详细列表信息  该方法不在当前实现类,调用
        CourseDescription courseDescription = courseDescriptionService.getById(id);
        if(courseDescription != null){//判断
            //将课程详细信息给了课程详细信息列表
            courseInfoForm.setDescription(courseDescription.getDescription());
        }

        return courseInfoForm;
    }

    @Override//根据id修改课程详细信息
    @CacheEvict(value = "course",allEntries = true)
    public void updateCourseInfoById(CourseInfoForm courseInfoForm) {
        // 1. 修改课程信息
        Course course = new Course();
        //将新修改的前端传过来的对象赋值给course
        BeanUtils.copyProperties(courseInfoForm,course);
        int i = baseMapper.updateById(course);
        if(i==0){
            throw new QinXueException(20001,"课程信息保存失败");
        }
        // 2. 修改课程描述信息
        CourseDescription courseDescription = new CourseDescription();
        courseDescription.setId(courseInfoForm.getId());
        courseDescription.setDescription(courseInfoForm.getDescription());
        boolean b = courseDescriptionService.updateById(courseDescription);
        if(!b){
            throw new QinXueException(20001,"课程详细信息保存失败");
        }
    }

    @Override//根据id查询课程展示页面信息
    public CoursePublishVo getCoursePublishVoById(String id) {
        CoursePublishVo coursePublishVo = baseMapper.selectCoursePublishVoById(id);
        if(coursePublishVo==null){
            throw new QinXueException(2000,"课程展示页面信息获取失败");
        }
        return coursePublishVo;
    }

    @Override//根据id发布课程
    @CacheEvict(value = "course",allEntries = true)
    public void publishCourseById(String id) {
        Course course = new Course();
        course.setId(id);
        course.setStatus(course.COURSE_NORMAL);//设置发布状态为已发布
        int i = baseMapper.updateById(course);
        if(i==0){
            throw new QinXueException(20001,"课程发布失败");
        }
    }

    @Override//分页模糊查询课程信息
    public void pageQuery(Page<Course> pageParam, CourseQuery courseQuery) {
        //根据创建课程时间将课程排序
        QueryWrapper<Course> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("gmt_create");

        if(courseQuery==null){//判断前端传过来的需要查询的课程条件是否为空
            baseMapper.selectPage(pageParam,queryWrapper);//将课程查询条件封装到分页插件里面
        }

        //判断模糊查询条件是否为空然后赋值
        if(!StringUtils.isEmpty(courseQuery.getTitle())){
            queryWrapper.like("title",courseQuery.getTitle());
        }
        if(!StringUtils.isEmpty(courseQuery.getSubjectId())){
            queryWrapper.eq("subject_id",courseQuery.getSubjectId());
        }
        if(!StringUtils.isEmpty(courseQuery.getSubjectParentId())){
            queryWrapper.eq("subject_parent_id",courseQuery.getSubjectParentId());
        }
        if(!StringUtils.isEmpty(courseQuery.getTeacherId())){
            queryWrapper.eq("teacher_id",courseQuery.getTeacherId());
        }
        baseMapper.selectPage(pageParam,queryWrapper);
    }

    @CacheEvict(value = "course",allEntries = true)
    @Override//根据课程id删除课程信息
    public void removeCourseById(String courseId) {
        //删除节目录信息
        videoService.removeByCourseId(courseId);
        //删除章目录
        chapterService.removeByCourseId(courseId);
        courseDescriptionService.removeById(courseId);
        //https://qinxue-syx.oss-cn-beijing.aliyuncs.com/avatar/2024/07/22/f9898fba-8484-451b-812e-cf336700cf5f.jpg
        //删除封面
        Course course = baseMapper.selectById(courseId);
        String cover = course.getCover();
        if(StringUtils.isNotEmpty(cover)){//有封面就删除
            if(!cover.endsWith("cover/default.jpg")){
                int index = cover.indexOf("cover");
                String s = cover.substring(index);
                ossClient.delete(s);
            }
        }
        //删除自己
        int i = baseMapper.deleteById(courseId);
        if(i==0){
            throw new QinXueException(20001,"课程信息删除失败");
        }
    }


    @Cacheable(value = "course",key = "'indexCourse'")
    public List<Course> indexList() {
        QueryWrapper<Course> courseQueryWrapper = new QueryWrapper<>();
        courseQueryWrapper.orderByDesc("id");
        //拼接语句]
        courseQueryWrapper.last(" limit 8 ");
        List<Course> list = baseMapper.selectList(courseQueryWrapper);
        return list;
    }

    @Override//根据讲师id查询课程
    public List<Course> selectByTeacherId(String teacherId) {
        QueryWrapper<Course> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("teacher_id",teacherId);
        queryWrapper.orderByDesc("gmt_modified");
        List<Course> list = baseMapper.selectList(queryWrapper);
        return list;
    }


    @Override//查询课程详细信息前台
    public Map<String, Object> pageListWeb(Page<Course> pageParam, CourseQueryVo courseQuery) {

        //先执行动态查询
        QueryWrapper<Course> queryWrapper = new QueryWrapper<>();

        if (!StringUtils.isEmpty(courseQuery.getSubjectParentId())) {
            queryWrapper.eq("subject_parent_id", courseQuery.getSubjectParentId());
        }

        if (!StringUtils.isEmpty(courseQuery.getSubjectId())) {
            queryWrapper.eq("subject_id", courseQuery.getSubjectId());
        }

        if (!StringUtils.isEmpty(courseQuery.getBuyCountSort())) {
            queryWrapper.orderByDesc("buy_count");
        }

        if (!StringUtils.isEmpty(courseQuery.getGmtCreateSort())) {
            queryWrapper.orderByDesc("gmt_create");
        }

        if (!StringUtils.isEmpty(courseQuery.getPriceSort())) {
            queryWrapper.orderByDesc("price");
        }

        baseMapper.selectPage(pageParam, queryWrapper);

        List<Course> records = pageParam.getRecords();
        long current = pageParam.getCurrent();
        long pages = pageParam.getPages();
        long size = pageParam.getSize();
        long total = pageParam.getTotal();
        boolean hasNext = pageParam.hasNext();
        boolean hasPrevious = pageParam.hasPrevious();

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("items", records);
        map.put("current", current);
        map.put("pages", pages);
        map.put("size", size);
        map.put("total", total);
        map.put("hasNext", hasNext);
        map.put("hasPrevious", hasPrevious);

        return map;
    }
}
